<template>

  <km-layout @scroll="handleScroll">
    <template v-slot:page>
      <div v-if="wspm">
        <div class="" v-for="(data,index) in datas" :key="index">
          <div style="font-weight:bold">第{{ index + 1 }}名</div>
          <div class="">标题：<a :href="data.href" target="_blank">{{ data.title }}</a></div>
          <div class="">阅读：{{ data.data.reads > 10000 ? data.data.reads / 10000 + '万' : data.data.reads }}</div>
          <div class="">收藏：{{
              data.data.collects > 10000 ? data.data.collects / 10000 + '万' : data.data.collects
            }}
          </div>
          <div class="">作者：<a :href="data.author.page" target="_blank">{{ data.author.name }}</a></div>
          <br/>
        </div>
      </div>
      <div v-if="newrank">
        <div class="" v-for="(data,index) in datas" :key="index">
          <div style="font-weight:bold">篇{{ index + 1 }}</div>
          <div class="">标题：<a :href="data.url" target="_blank">{{ data.title }}</a></div>
          <div class="">阅读：10万+</div>
          <div class="">喜欢：{{ data.data.likes }}</div>
          <div class="">公众号：<a :href="data.author.page" target="_blank">{{ data.author.name }}</a></div>
          <br/>
        </div>
      </div>
      <div v-show="hasContent">
        <div class="row paths">
            <span class="path" v-if="data.parents.length > 0">
              <a href="/km">首页</a>
            </span>
          <span class="path" v-for="parent in data.parents" :key="parent._id">
              <a :href="'/km/article?id=' + parent._id + '&sid=' + data.kmSpaceId">&nbsp;&nbsp;>&nbsp;&nbsp;{{
                  parent.title
                }}</a>
            </span>
        </div>
        <!-- TODO data.title改为''，编辑或创建新文章功能就失效，诡异得很哪。 -->
        <div class="title">{{ data.status === 8 ? '已下线·' : (data.status === 1 ? '未发布·' : '') }}{{
            data.title === '' || data.title === undefined ? 'Loading ...' : data.title
          }}<span v-if='hasDraft && $store.state.userInfo.role === 0' class="draft"
                  @click="handleShow">{{ showHint }}</span> <!-- <span>前往引用的文章原文</span> -->
        </div>
        <!-- <div class="row tags" > <div v-for="tag in data.tags" :key="tag">{{ tag }}</div></div> -->
        <div class="content" v-html="data.content"></div>
        <slot v-if="showFooterAds" name="footer"></slot>
        <km-toolbar class="km-footer" :data="data"></km-toolbar>
      </div>
      <div v-show="!hasContent" class="no-data">文章不存在</div>
    </template>
    <!-- <template v-slot:bottom>
      <div class="row actions">
            <div class="action">点赞 {{ data.statistics.votes }}</div>
            <div class="">收藏</div>
            <div class="">分享</div>
            <div class="">克隆</div>
          </div>
    </template> -->
    <template v-slot:control v-if="$store.state.userInfo.role === 0">
      <q-item clickable v-ripple
              :to="{name:'CreateKM', params: {action: 'create', parent: data._id, kmSpaceId: data.kmSpaceId}}">
        <q-item-section avatar>
          <q-avatar color="deep-orange" text-color="white" icon="local_activity"/>
        </q-item-section>
        <q-item-section>创建</q-item-section>
      </q-item>
      <q-item clickable v-ripple :to="{name:'CreateKM', query: {id: data._id}, params: {action: 'edit'}}">
        <q-item-section avatar>
          <q-avatar color="deep-orange" text-color="white" icon="local_activity"/>
        </q-item-section>
        <q-item-section>编辑</q-item-section>
      </q-item>
      <q-item v-if="data.status===6" clickable v-ripple @click="handleContent(8)">
        <q-item-section avatar>
          <q-avatar color="deep-orange" text-color="white" icon="local_activity"/>
        </q-item-section>
        <q-item-section>下线</q-item-section>
      </q-item>
      <q-item v-if="data.status===8" clickable v-ripple @click="handleContent(6)">
        <q-item-section avatar>
          <q-avatar color="deep-orange" text-color="white" icon="local_activity"/>
        </q-item-section>
        <q-item-section>重新上线</q-item-section>
      </q-item>
      <q-item v-if="data.status===6" class="shareZhihu"
              clickable v-ripple @click="share(1)" :data-clipboard-text="shareZhihu">
        <q-item-section avatar>
          <q-avatar color="deep-orange" text-color="white" icon="local_activity"/>
        </q-item-section>
        <q-item-section>分享至知乎</q-item-section>
      </q-item>
      <q-item v-if="data.status===6 && $store.state.userInfo.name === 'leo'"
              clickable v-ripple @click="handleWspm">
        <q-item-section avatar>
          <q-avatar color="deep-orange" text-color="white" icon="local_activity"/>
        </q-item-section>
        <q-item-section>woshipm</q-item-section>
      </q-item>
      <q-item v-if="data.status===6 && $store.state.userInfo.name === 'leo'"
              clickable v-ripple @click="handleNewrank">
        <q-item-section avatar>
          <q-avatar color="deep-orange" text-color="white" icon="local_activity"/>
        </q-item-section>
        <q-item-section>10万+</q-item-section>
      </q-item>
      <q-input ref="" dense filled v-model="date" placeholder="输入日期"/>
      <!-- <q-btn label="克隆"/> -->
      <!-- <q-btn label="新建"/> -->
      <!-- <q-btn label="引用"/> -->
      <!-- <q-btn label=""/> -->
      <div class="q-mt-sm">
        <div class="text-subtitle1">标签</div>
        <tool-tag-chip-group v-model="data.tags"></tool-tag-chip-group>
      </div>
    </template>
    <template v-slot:newest class="newest">
      <newest-components class="newest"></newest-components>
    </template>
    <template v-slot:statistics class="statistics">
      <!-- <newest-components class="statistics"></newest-components> -->
    </template>

    <template v-if="adsShow" v-slot:footer>
      <div v-if="ads._id.length > 0" @click="handleAds" class="ads-div">
        <span class="ads-content">{{ ads.content }}</span>
        <span class='ads-author'>by {{ ads.by }}</span>
        <!-- <a href="https://union-click.jd.com/jdc?e=&p=JF8BALUJK1olXDYCVVxaCEIeA19MRANLAjZbERscSkAJHTNYRgYKBlMdBgABFhNIVjtBB1sUXwECXVddFxJSXzI4GD5gXmFXMls9ew9XADtUHFJHHwBwAlJROE4XAm4MGFISWAIyV19dDkMfAmsPGmslXQcyFTBdCU8RB2wAHWsXXAcAXF1VD04VM28PGVkVWQEBXVxdC00nBG8BKxlMCUVeDAFtOHsUM184GGsWbVlGCQNtCkoWB2Y4" target="_blank">1111</a> -->
      </div>
    </template>
  </km-layout>
</template>
<script>
import ToolTagChipGroup from 'src/components/tag/ToolTagChipGroup.vue'
import { defineComponent } from 'vue'
import iContent from 'src/api/content'
import iWoshipm from 'src/api/km/woshipm'
import KmLayout from 'src/layouts/KmLayout.vue'
import AppActivityMixin from 'src/mixins/app-activity'
import 'highlight.js/styles/monokai-sublime.css'
import 'highlight.js/styles/base16/monokai.css'
import NewestComponents from './NewestComponents.vue'
import KmToolbar from './ToolbarComopents.vue'
import ClipboardJS from 'clipboard'

export default defineComponent({
  mixins: [AppActivityMixin],
  components: {
    KmLayout,
    ToolTagChipGroup,
    NewestComponents,
    KmToolbar
  },
  data () {
    return {
      datas: [],
      date: '',
      data: {
        draft: '',
        content: '',
        title: '',
        _id: '',
        status: null,
        tags: [],
        statistics: {
          votes: '',
          comments: '',
          collects: ''
        },
        parents: [],
        kmSpaceId: ''
      },
      tmp: '',
      showHint: '查看草稿',
      hasDraft: false,
      hasContent: true,
      start: Date.now(),
      shareZhihu: '',
      wspm: false,
      newrank: false,
      ads: {
        _id: '',
        type: '',
        content: '',
        by: '',
        href: ''
      },
      adsShow: false,
      space: null,
      showFooterAds: false
    }
  },
  watch: {
    $route () {
      this.getArticle(this.$route.query.id)
      this.getAds()
    }
  },
  async mounted () {
    const spaces = await iContent.getKmSpaces()
    this.space = spaces.filter(e => e.type === 1)[0]
    let cid = this.$route.query.id
    if (!cid || cid === '') {
      cid = this.space.homepageId
    }
    this.$router.push({
      path: '/km/article',
      query: {
        id: cid,
        sid: this.space._id
      }
    })
    await this.getArticle(cid)
    this.getAds()
  },
  methods: {
    async handleNewrank () {
      this.newrank = !this.newrank
      if (!this.newrank) return
      console.log('getList')
      const query = {}
      query.type = 'newrank'
      query.sorts = { data: { likes: -1 } }
      query.day = this.date
      query.subject = '今日热门文章'
      const data = await iWoshipm.getList(query)
      this.datas = data
      console.log(this.datas)
    },
    async handleWspm () {
      this.wspm = !this.wspm
      if (!this.wspm) return
      console.log('getList')
      const query = {}
      query.sorts = { data: { reads: -1 } }
      query.day = '2021-09-27'
      query.subject = '阅读量前100'
      const data = await iWoshipm.getList(query)
      this.datas = data
      console.log(this.datas)
    },
    share (to) {
      // zhihu 1
      const url = location.origin + location.pathname + '?r=' + to + '&' + location.search.substring(1)
      this.shareZhihu = url
      const clipboard = new ClipboardJS('.shareZhihu', {
        text: function () {
          return url
        }
      })
      // 复制成功
      clipboard.on('success', () => {
        this.$q.notify({
          icon: 'insert_emoticon',
          message: '复制链接成功',
          color: 'info',
          position: 'top',
          timeout: 1000
        })
        // 释放内存
        clipboard.destroy()
      })
      clipboard.on('error', () => {
        this.$q.notify({
          icon: 'insert_emoticon',
          message: '复制链接失败，请重试。',
          color: 'warning',
          position: 'top',
          timeout: 1000
        })
        clipboard.destroy()
      })
    },
    async handleContent (status) {
      const content = {
        _id: this.data._id,
        status: status
      }
      await iContent.update(content)
      this.$store.dispatch('km/initMenu', {
        status: this.visiting,
        kmSpaceId: this.$route.query.sid
      })
      this.getArticle(this.data._id)
    },
    async handleShow () {
      if (this.showHint === '查看草稿') {
        this.tmp = this.data.content
        this.showHint = '返回原文'
        this.data.content = this.data.draft
      } else {
        this.showHint = '查看草稿'
        this.data.draft = this.data.content
        this.data.content = this.tmp
      }
    },
    async getArticle (cid) {
      let query = { id: cid }
      if (!cid) query = {}
      console.log('getArticle', query)
      const data = await iContent.findContents(query)
      if (data) {
        this.hasContent = true
        this.data = data
        this.hasDraft = false
        this.data.parents = this.data.parents.reverse()
        if (data.draft && (data.draft.length > 0)) {
          this.hasDraft = true
        } else {
          this.hasDraft = false
        }
        this.logVisit()
        this.start = Date.now()
      } else {
        this.hasContent = false
      }
    },
    async logVisit () {
      const v = { id: this.data._id }
      if (this.$route.query.r) v.from = this.$route.query.r
      this.log({
        module: 'km',
        page: 'content',
        element: 'page',
        event: 'show'
      }, 'show-content', v)
    },
    async handleScroll () {
      const end = Date.now()
      this.log({
            module: 'km',
            page: 'content',
            element: 'page',
            event: 'scroll'
          },
          'view-content', {
            id: this.data._id,
            start: this.start,
            end: end,
            duration: end - this.start
          })
      this.start = end
    },
    async getAds () {
      const data = await iContent.getAds({ contentId: this.data._id })
      console.log(data)
      this.ads = data
      //
      const v = {
        contentId: this.data._id,
        adsId: this.ads._id,
        type: this.ads.type,
        role: this.$store.state.userInfo.role
      }
      this.log({
        module: 'km',
        page: 'content',
        element: 'footer-ads',
        event: 'show'
      }, 'show-ads', v)
    },
    async handleAds () {
      await window.open(this.ads.href, '_blank')
      //
      const v = {
        contentId: this.data._id,
        adsId: this.ads._id,
        type: this.ads.type,
        role: this.$store.state.userInfo.role
      }
      this.log({
        module: 'km',
        page: 'content',
        element: 'footer-ads',
        event: 'click'
      }, 'open-ads', v)
    }
  },
  unmounted () {
    this.log({
      module: 'km',
      page: 'view',
      element: '',
      event: ''
    }, 'leave-content', { id: this.data._id })
  }
})
</script>

<style lang="scss">
.title {
  color: #222222;
  font-weight: bolder;
  margin-top: 22px;
  margin-bottom: 22px;
  font-size: 28px;
  line-height: 28px;
  letter-spacing: .034em;
  font-family: PingFang SC, Microsoft YaHei, -apple-system, BlinkMacSystemFont, Helvetica Neue, Source Han Sans SC, Noto Sans CJK SC, WenQuanYi Micro Hei, sans-serif;
  word-wrap: break-word;
  hyphens: auto;
  padding: 0;
  outline: 0;
}

.draft {
  margin-left: 20px;
  font-size: 14px;
  text-decoration: underline;
  text-underline-offset: 1px;
}

.paths {
  margin-top: 10px;
  margin-bottom: 20px;

  .path {
    font-size: 14px;
  }
}

.tags {
  margin-bottom: 10px;

  div {
    border-radius: 20px;
    margin-right: 10px;
    padding: 0 15px;
    height: 32px;
    line-height: 32px;
    background-color: rgba($c1, 0.2);
    color: $c1;
    font-weight: bold;
  }
}

.content {
  font-family: PingFang SC, Microsoft YaHei;
  font-weight: 400;
  font-size: 16px;
  color: #131313;
  padding: 0;
  line-height: 1.6;
  word-break: break-all;

  div, p {
    margin: 0 0 22px 0;
    padding: 0;
    text-align: justify;
    font-size: 16px !important;
  }

  figure {
    margin: 0;
    text-align: center;

    p {
      text-align: center;
    }
  }

  img, figure {
    text-align: center;
  }

  img {
    width: 100%;
    height: auto;
  }

  blockquote {
    margin: 1.4em 0;
    padding-left: 1em;
    color: #646464;
    border-left: 3px solid #d3d3d3;
  }

  pre {
    margin: 1.4em 0;
    padding: 10px;
    background: #f6f6f6;
    border-radius: 4px;
    white-space: pre-wrap;
    word-wrap: break-word;

    code, p {
      font-size: 13px;
    }
  }

  h1, h1 p {
    clear: left;
    margin-top: 22px;
    margin-bottom: 22px;
    font-size: 20px !important;
    line-height: 1.5;
    font-weight: bolder;
    font-synthesis: style;
  }

  h2, h2 p {
    clear: left;
    margin-top: 22px;
    margin-bottom: 22px;
    font-size: 18px !important;
    line-height: 1.5;
    font-weight: bolder;
    font-synthesis: style;
  }

  a, a:visited, a:hover, a:active, a:focus {
    color: #131313;
    text-decoration: none;
    background-color: white !important;
    margin-top: -22px;
    border-bottom: 1px solid rgba(#808080, 0.8);
  }
}

// 与wangeditor的字号级别对应
font[size="3"] {
  font-size: 16px;
  margin: 0;
  padding: 0;
}

.no-data {
  color: $nonce;
  font-size: 20px;
  margin-top: 200px;
  margin-left: 300px;
}

// .actions {
//   z-index: 2;
//   margin-top: 10px;
//   background-color: $c5;
// }

.newest {
  width: 300px;
}

.ads-div {
  line-height: 50px;
  text-align: center;
}

.ads-content {
  padding-left: 10px;
  color: white;
  font-size: 14px;
  font-weight: bold;
}

.ads-author {
  padding-left: 10px;
  color: white;
  font-size: 12px;
}

.km-footer {
  position: fixed;
  bottom: 0px;
  padding: 0;
  max-width: 640px;
  height: 40px;
}
</style>
